<?php
/**
 * Created by PhpStorm.
 * User: kiki
 * Date: 2022/7/19
 */

namespace App\Common\Service\Tool;

use App\Common\Service\BaseService;
use EasySwoole\Smtp\Mailer;
use Mine\Exception\NormalStatusException;

// 文档 https://www.easyswoole.com/Components/Stmp/smtp.html

class SmtpService extends BaseService
{
    const SERVER = 'smtp.qq.com'; // smtp 服务器地址

    const MAIL_FROM = '522402295@qq.com'; // 发送邮箱、用户名

    const TITLE = 'kiki团队邮件'; // 默认标题

    const USER_NAME = 'kiki';

    const PASSWORD = 'ecjbekmgfwnxbgej'; // 登录授权码

    /**
     * @param $toEmail 收件人邮箱|必须
     * @param $content 发送内容|必须
     * @param string $title 标题
     */
    public static function email($toEmail, $title = '', $content = '', $file = '', $textType = 'text')
    {
        if (empty($toEmail) || empty($content)) {
            throw new \Exception('收件人邮箱不能为空或邮件内容不能为空');
        }
        // 协程发送
        go(function () use ($toEmail, $content, $title, $textType, $file) {
            if (empty($title)) {
                $title = self::TITLE;
            }
            $mail = new Mailer(true);
            $mail->setTimeout(5);
            $mail->setHost("smtp.qq.com");
            $mail->setPort(465);
            $mail->setSsl(true);
            $mail->setUsername(self::MAIL_FROM);
            $mail->setPassword(self::PASSWORD);
            $mail->setFrom(self::MAIL_FROM); // 设置发件人地址
            $mail->addAddress($toEmail); // 收件人地址
            $mail->setReplyTo(self::MAIL_FROM); // 回复地址

            try {
                if ($textType == 'text') {
                    // 文本
                    $text = new \EasySwoole\Smtp\Request\Text();
                    $text->setSubject($title);
                    $text->setBody($content);
                    if ($file) {
                        $text->addAttachment($file);// 添加附件 可选
                    }
                    $mail->send($text);
                } else {
                    // html
                    $text = new \EasySwoole\Smtp\Request\Html();
                    $text->setSubject($title);
                    $text->setBody($content);
                    if ($file) {
                        $text->addAttachment($file);// 添加附件 可选
                    }
                    $mail->send($text);
                }
            } catch (\EasySwoole\Smtp\Exception\Exception $exception) {
                throw new NormalStatusException($exception->getMessage());
            }
        });
    }
}